import fs from 'fs'
import os from 'os';
import path from 'path';
import express from 'express'
import { promisify } from 'util'
import { v4 as uuid } from 'uuid';
import childProcess from 'child_process';
import fileUpload from 'express-fileupload'
import iconv from 'iconv-lite'; // 需要安装iconv-lite库


// 服务根目录
const rootPath = process.cwd();

const app = express();

// 使用static中间件： 把www文和uploads件夹作为静态资源服务器来访问
app.use(express.static('www'))
app.use('/upload', express.static('upload'));
// 使用express-fileupload中间件
app.use(fileUpload({ defParamCharset: "utf8" }));

// 定义路由
app.get('/', (req, res) => {
    res.render('index');
})

// 定义路由
app.get('/test', (req, res) => {
    res.send('<h1>你好，世界</h1>')
})

app.post('/resigner', async (req, res) => {
 
    const packageName = req.body.packageName;

    console.log('参数，', req.body);

    // 创建一个目录 根据时间戳+随机数
    const dirName = `${new Date().getTime()}_${uuid()}`; // 创建的临时目录名
    const dirPath = path.join(rootPath, 'upload', dirName) // 创建该目录
    fs.mkdirSync(dirPath, { recursive: true })

    // 接收和保存文件
    const file = req.files.file;
    const fileName = file.name;
    const fileNameNoSuffix = fileName.replace(/\.[^/.]+$/, "");

    const filePath = path.join(dirPath, fileName);
    await promisify(file.mv)(filePath);

    let isRe = Boolean(packageName); // 是否逆向
    // 操作shell
    if (os.type() === 'Windows_NT') {
        // 先改包名
        if (packageName) {
            console.log('进入逆向流程...');
            const param = [
                '-File', './shell/change-pkg.ps1', // 替换为你的批处理文件路径
                dirPath, fileNameNoSuffix, packageName
            ];
            const option = {
                encoding: 'utf8', // 如果脚本里有中文 一定要设置成这个
                env: {
                    ...process.env,
                    LANG: 'zh_CN.UTF-8', // 要设置这个 否则shell的ui界面会乱码
                }
            };
            const output = childProcess.execFileSync('powershell', param, option);
            console.log(output.toString());

        }

        const param = [
            '-File', './shell/re-signer.ps1', // 替换为你的批处理文件路径
            dirPath, (isRe?'逆向-':'')+fileNameNoSuffix, req.body.type
        ];
        const option = {
            encoding: 'utf8', // 如果脚本里有中文 一定要设置成这个
            env: {
                ...process.env,
                LANG: 'zh_CN.UTF-8', // 要设置这个 否则shell的ui界面会乱码
            }
        };
        // const output = childProcess.execFileSync('powershell', param, option);
        // console.log(output.toString());

    } else {
        if (packageName) {
            childProcess.exec('chmod 777 ./shell/change-pkg.sh')
            const output = childProcess.execFileSync('./shell/change-pkg.sh', [dirPath, fileNameNoSuffix, packageName], { encoding: 'utf-8' });
            console.log(output.toString());
        }
        childProcess.exec('chmod 777 ./shell/re-signer.sh')
        const output = childProcess.execFileSync('./shell/re-signer.sh', [dirPath, (isRe?'逆向-':'')+fileNameNoSuffix, req.body.type], { encoding: 'utf-8' });
        console.log(output.toString());
    }



    res.json({
        msg: '处理完成',
        code: 0,
        data: {
            dowonload: path.join('/upload', dirName, '签名-'+(isRe?'逆向-':'')+ fileName)
        }
    });
})


app.listen(3000, () => console.log('服务已经启动： http://127.0.0.1:3000'))